package com.hopechart.micro.web.controller;

import com.hopechart.micro.common.constant.HttpStatus;
import com.hopechart.micro.common.generator.GeneratorLauncher;
import com.hopechart.micro.config.MasterDataSourceConfig;
import com.hopechart.micro.domain.entities.master.Gps;
import com.hopechart.micro.util.CacheUtil;
import com.hopechart.micro.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * <br/>Index
 * </p>
 *
 * @author daijiang@hopechart.com
 * @version V1.0.0
 * @date 2017-11-29 10:27
 * @copyright 杭州鸿泉数字设备有限公司
 */
@Controller
@RequestMapping(value = "")
public class IndexController extends BaseController{

    @Autowired
    private MasterDataSourceConfig dataSourceConfig;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index() {
        return getModelAndView("index").addObject("message", "this is demo");
    }

    /**
     * 代码自动生成
     * @param tableName
     * @return
     */
    @RequestMapping(value = "/code", method = RequestMethod.GET)
    public String generatorCode(@RequestParam(value = "tableName", required = true) String tableName,
                                @RequestParam(value = "modelName", required = false) String modelName) {

        new GeneratorLauncher().executor(dataSourceConfig, tableName, modelName);
        return JsonUtil.toString(response(HttpStatus.HTTP_STATUS_200, "代码已生成"));
    }

    @ResponseBody
    @RequestMapping(value = "/loading", method = RequestMethod.GET)
    public List<Gps> loadGps() {
        Map<String, Object> map = (Map)CacheUtil.getValue("gpsCache", "gpsCache");
        List<Gps> gpsList = (List)map.get("gps");
        return gpsList;
    }

    @ResponseBody
    @RequestMapping(value = "/loading/point", method = RequestMethod.GET)
    public List<String> loadPoint() {
        Map<String, Object> map = (Map)CacheUtil.getValue("gpsCache", "gpsCache");
        List<String> points = (List<String>) map.get("point");
        return points;
    }

    @ResponseBody
    @RequestMapping(value = "/cache/refresh", method = RequestMethod.GET)
    public List<String> refreshCache() {
        CacheUtil.refresh("gpsCache", "gpsCache");
        Map<String, Object> map = (Map)CacheUtil.getValue("gpsCache", "gpsCache");
        List<String> points = (List<String>) map.get("point");
        return points;
    }

}